package cn.schoolwow.quickdao.module.database.dcl.service;

import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetUserNameListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        flowContext.putTemporaryData("name", "获取数据库用户列表");

        switch (databaseType){
            case Mysql:{
                flowContext.putTemporaryData("sql", "select distinct user from mysql.user;");
            };break;
            case Postgresql:{
                flowContext.putTemporaryData("sql", "select usename from pg_user;");
            };break;
            default:{
                throw new UnsupportedOperationException("当前数据库不支持获取数据库用户列表!数据库类型:"+databaseType.name());
            }
        }

        final List<String> userNameList = new ArrayList<>();
        flowContext.putData("userNameList", userNameList);
        flowContext.putReturnData("resultSetConsumer",new ResultSetConsumer() {
            @Override
            public void consumeResultSet(ResultSet resultSet) throws SQLException {
                while (resultSet.next()) {
                    userNameList.add(resultSet.getString(1));
                }
            }
        });

        flowContext.executeFlowList(new ExecuteQueryConnectionFlow());
    }

    @Override
    public String name() {
        return "获取数据库用户列表";
    }
}
